<template>
	<view class="content">

		<view class="machine_top">
			<image src="../../static/patrol/equipment.png" mode="" class="machine_top_img"></image>
			<text class="machine_top_name">{{dataInfo.name}}</text>
			<view class="state_but">
				<u-button size="small" type="success" @click="submit()">全部完成</u-button>
			</view>
		</view>
		<view class="machine_info">
			<view class="" v-for="(item,index) in machineList" class="modular" style="margin: 30rpx 0;"
				v-if="machineList.length > 0">
				<view class="machine_item">
					<view class="machine_title"></view>
					<view class="machine_name">{{item.equipmentType}}{{item.equipmentNo}}</view>
					<view class="machine_but">
						<u-button size="small" type="success" @click="scanCode(item)">扫码编辑</u-button>
					</view>
				</view>
				<view class="list-cell b-b" hover-class="cell-hover" :hover-stay-time="50"
					v-if="item.inspectionItems.indexOf('温度') != -1">
					<text class="cell-tit">
						温度（℃）
					</text>
					<!--  -->
					<u-input placeholder="请输入温度" border="none" type="number" :readonly="item.qrCode" maxlength="8" inputAlign="right"
						v-model="item.temperature">
					</u-input>
				</view>
				<view class="list-cell b-b" hover-class="cell-hover" :hover-stay-time="50"
					v-if="item.inspectionItems.indexOf('湿度') != -1">
					<text class="cell-tit">
						湿度（%）
					</text>
					<u-input placeholder="请输入湿度" border="none" :readonly="item.qrCode" type="number" maxlength="8" inputAlign="right"
						v-model="item.humidity"></u-input>
				</view>
				<view class="list-cell b-b" hover-class="cell-hover" :hover-stay-time="50"
					v-if="item.inspectionItems.indexOf('运行状态') != -1">
					<text class="cell-tit">
						运行状态
					</text>
					<view>
						<u-radio-group v-model="item.runningStatus" :disabled="item.qrCode" placement="row" @change="groupChange(index,$event)">
							<u-radio :customStyle="{marginLeft: '40rpx'}" v-for="(item1, index1) in radiolist1"
								:key="index1" :label="item1.name" :name="item1.name">
							</u-radio>
						</u-radio-group>
					</view>
				</view>
				<view class="file">
					<text class="title">上传附件</text>
					<view class="file_upload">
						<u-upload :fileList="fileList[`fileList${index}`]" :disabled="item.qrCode" @afterRead="afterRead($event,index)"
							@delete="deletePic" accept="image" capture="camera" :name="index+''" multiple :maxCount="3">
						</u-upload>
					</view>

				</view>
			</view>

			<view style="text-align: center;font-size: 15px;" v-if="machineList.length ==0">暂无设备~</view>
		</view>
		<u-toast ref="uToast"></u-toast>

	</view>
</template>

<script>
	import config from '@/config/.env.dev.js'
	export default {
		data() {
			return {
				dataInfo: {},
				machineList: [],
				radiolist1: [{
						name: "正常",
						disabled: false
					},
					{
						name: "异常",
						disabled: false
					}
				],
				fileList: {
					fileList0: [],
					// fileList1: [],
				},
				urlList: [],
			}
		},
		onLoad(options) {
			if (options._obj) {
				this.dataInfo = JSON.parse(options._obj)
				this.getList()
			}
		},
		methods: {
			getList() {
				var that = this
				this.$api.request('app.equipment', 'allEquipment', {
					// page: 1,
					// limit: 20
					roomName: this.dataInfo.name
				}).then(res => {
					if (res.data.length > 0) {
						that.machineList = res.data

						for (let i = 0; i < that.machineList.length; i++) {
							that.$set(that.fileList, `fileList${i}`, [])
						}
					}
				})
			},
			submit() {
				var paramList = []
				for (let i = 0; i < this.machineList.length; i++) {
					var param = {}
					if (this.machineList[i].inspectionItems.indexOf('温度') != -1 && !this.machineList[i].temperature) {
						this.$api.msg("请输入" + this.machineList[i].equipmentType + this.machineList[i].equipmentNo +
							" 设备的温度")
						return
					}
					if (this.machineList[i].inspectionItems.indexOf('湿度') != -1 && !this.machineList[i].humidity) {
						this.$api.msg("请输入" + this.machineList[i].equipmentType + this.machineList[i].equipmentNo +
							"设备的湿度")
						return
					}
					if (!this.machineList[i].runningStatus || this.machineList[i].runningStatus == "undefined") {
						this.$api.msg("请勾选" + this.machineList[i].equipmentType + this.machineList[i].equipmentNo +
							"设备的运行状态")
						return
					}
					param.photo = this.urlList[i]
					if (!param.photo) {
						this.$api.msg("请上传" + this.machineList[i].equipmentType + this.machineList[i].equipmentNo +
							"的附件")
						return
					}
					param.roundsId = this.machineList[i].roundsId
					param.roomName = this.machineList[i].roomName
					param.roomId = this.machineList[i].roomId
					param.equipmentType = this.machineList[i].equipmentType
					param.equipmentNo = this.machineList[i].equipmentNo
					param.equipmentId = this.machineList[i].id
					param.temperature = this.machineList[i].temperature
					param.humidity = this.machineList[i].humidity
					if (this.machineList[i].runningStatus == "正常") {
						param.runningStatus = "1"
					} else {
						param.runningStatus = "2"
					}


					paramList.push(param)
				}
				uni.showLoading({
					title: '加载中',
					mask: true
				})
				this.$api.request('app.inspection', 'create', {
					str: JSON.stringify(paramList)
				}).then(res => {
					uni.hideLoading()
					this.$refs.uToast.show({
						type: 'success',
						message: "提交成功",
						complete() {
							uni.navigateBack({
								delta: 1
							})
						}
					})
				}).catch(res => {
					uni.hideLoading()
				})
			},
			scanCode(val) { //扫码
				let _this = this;
				uni.scanCode({
					onlyFromCamera: true,
					scanType: ['qrCode'],
					success: function(res) {
						if (res.result) {
							let qrId = res.result.split(":")[1]
							console.log('条码内容：' + qrId);
							console.log('设备id' + val.id)
							console.log(val.id == qrId)
							if (val.id == qrId) {
								_this.$api.msg("扫描成功！")
								val.qrCode = false
								_this.$forceUpdate()
							} else {
								_this.$api.msg("扫描不匹配！")
							}
						} else {
							_this.$api.msg("扫描失败！")
						}
					}
				});
			},
			groupChange(index, e) {
				this.machineList[index].runningStatus = e
			},
			// 删除图片
			deletePic(event) {
				let arr = this.urlList[event.name].split(",")
				arr.splice(event.index, 1)
				this.urlList[event.name] = arr.toString()
				this.fileList[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event, index) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.fileList[`fileList${event.name}`].length
				lists.map((item) => {
					this.fileList[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, index)
					let item = this.fileList[`fileList${event.name}`][fileListLen]
					this.fileList[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, index) {
				let userInfo = uni.getStorageSync("userInfo")
				let that = this
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + '/upload/admin', // 仅为示例，非真实的接口地址
						//url: 'https://taohaoliang.oss-cn-beijing.aliyuncs.com', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							ADMINTOKEN: userInfo.accessToken
						},
						formData: {
							user: 'test'
						},
						success: (res) => {
							let url = JSON.parse(res.data).url
							if (!that.urlList[index]) {
								that.urlList[index] = url
							} else {
								that.urlList[index] = that.urlList[index] + "," + url
							}
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)

						}
					});
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background: $page-color-base;
	}

	// .content{
	// 	padding: 20rpx;
	// }
	.machine_top {
		padding: 20rpx;
		display: flex;

		.machine_top_img {
			width: 50rpx;
			height: 50rpx;
		}

		.machine_top_name {
			margin-left: 30rpx;
		}

		// .machine_top_left{
		// 	display: flex;
		// }
		.state_but {
			justify-content: flex-end;
			margin-left: auto;
		}
	}

	.machine_info {
		background-color: #ffffff;
		padding: 20rpx 0;
		margin-top: 30rpx;

		.modular {
			margin-top: 30rpx;
		}

		.machine_item {
			display: flex;

			.machine_title {
				width: 10rpx;
				height: 40rpx;
				background: #2F53EB;
				margin-left: 20rpx;
			}

			.machine_name {
				margin-left: 20rpx;
			}

			.machine_but {
				display: flex;
				justify-content: flex-end;
				margin-left: auto;
				margin-right: 20rpx;
			}
		}
	}

	.list-cell {
		display: flex;
		align-items: baseline;
		padding: 20upx $page-row-spacing;
		line-height: 60upx;
		position: relative;
		background: #fff;
		justify-content: center;

		&.log-out-btn {
			margin-top: 40upx;

			.cell-tit {
				color: $uni-color-primary;
				text-align: center;
				margin-right: 0;
			}
		}

		&.cell-hover {
			background: #fafafa;
		}

		&.b-b:after {
			left: 30upx;
		}

		&.m-t {
			margin-top: 16upx;
		}

		.cell-more {
			align-self: baseline;
			font-size: $font-lg;
			color: $font-color-light;
			margin-left: 10upx;
		}

		.cell-tit {
			flex: 1;
			font-size: $font-base + 2upx;
			color: $font-color-dark;
			margin-right: 10upx;
		}

		.cell-tip {
			font-size: $font-base;
			color: $font-color-light;
		}

		switch {
			transform: translateX(16upx) scale(.84);
		}
	}

	.file {
		padding: 0 30rpx;
		margin-top: 20rpx;

		.title {
			font-size: 15px;
		}

		.file_upload {
			margin-top: 20rpx;
		}
	}
</style>
